package com.suredy.base.ctrl;

import java.rmi.RemoteException;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.suredy.Constants;
import com.suredy.PropertiesLoader;
import com.suredy.base.model.User;
import com.suredy.base.service.UserSrv;
import com.suredy.core.ctrl.BaseCtrl;

import eabnp.basic.result.IResult;
import eabnp.eflow.client.impl.local.IEFlowClientRmi;
import eabnp.eflow.session.ESession;

@Controller
public class LoginCtrl extends BaseCtrl {

	@Autowired
	private UserSrv userSrv;
	
	@RequestMapping({"/logout"})
	public ModelAndView logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		ModelAndView view = new ModelAndView("login");
		return view;
	}

	@RequestMapping({"/login"})
	public ModelAndView login(String userCode, String pwd) {
		ModelAndView login = new ModelAndView("login");

		if (StringUtils.isBlank(userCode) || StringUtils.isBlank(pwd))
			return login;
		String errMsg = null;
		try {
			AuthenticationToken token = new UsernamePasswordToken(userCode, pwd);// username和password是从表单提交过来的
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
		} catch(UnknownAccountException e) {
			errMsg = "帐号错误";
			login.addObject("errMsg", errMsg);
			return login;
		} catch(IncorrectCredentialsException e) {
			errMsg = "密码错误,请重新输入！";
			login.addObject("errMsg", errMsg);
			return login;
		}
		
		
		User user = this.userSrv.getUser(userCode, pwd);
		

		if (user == null) {
			errMsg = "帐号密码不匹配";
			login.addObject("errMsg", errMsg);
			return login;
		}

		IEFlowClientRmi client = getEFlowClient();

		if (client == null) {
			errMsg = "登录失败！无法获取流程信息!";
			login.addObject("errMsg", errMsg);
			return login;
		}

		try {
			IResult result = client.Exec("getSysCtrlInfo", new Object[] {user.getUserCode(), PropertiesLoader.getString(Constants.SYS_CODE)});

			if (result.isSuccess()) {
				setUser(user);
				setESession((ESession) result.getResultObject());
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		return new ModelAndView(new RedirectView("index.do"));
	}

	@RequestMapping({"/default"})
	public ModelAndView def() {
		ModelAndView view = new ModelAndView("login");
		return view;
	}
}
